#!/usr/bin/env python
# -*- coding: UTF-8 -*-

try:
	import pygame
	import sys
	from langanimateable import Animateable, AnimateableDiag
	from langtile import Tile
	#~ from cursor import *
	from pygame.locals import *
	from langutils import *
except ImportError, err:
	print "Could not load %s module." % (err)
	sys.exit(2)

'''
Battlefield

A simple and hopefully reusable object that loads the scenario map
and handles its own movement.

In the future, it might receive a two-dimensional array of map-tile
IDs and build the map from that.
'''

class Battlefield(pygame.sprite.DirtySprite, AnimateableDiag):
	def __init__(self, name):
		pygame.sprite.DirtySprite.__init__(self)
		AnimateableDiag.__init__(self)
		self.set_anim_params(FLD_TILE_SZ)

		self.mod = 0
		self.tiles = []
		self.tile_list = []
		self.tile_set = None
		self.map_w = 0
		self.map_h = 0
		self.import_hf('./data/maps/LAND01')
		self.import_tileset('./data/maps/ST01.pcx')
		self.image = self.generate_map()

		self.rect = self.image.get_rect()
		self.screen_rect = pygame.display.get_surface().get_rect()
		# how many pixels remain outside the screen when we are at
		# the bottom right corner of the map?
		self.right_overage = self.screen_rect.width % 48
		self.bottom_overage = self.screen_rect.height % 48

	def __getitem__(self, x):
		return self.tiles[x]

	def import_hf(self, hf_file):
		"""
		Imports an HF file (Used for Lang1 & Lang2 PC)
		"""

		from struct import unpack

		f = open(hf_file + ".hf", 'rb')

		self.map_w  = unpack("<I", f.read(4))[0]
		self.map_h  = unpack("<I", f.read(4))[0]
		f.seek(0x10)

		tile_list = []

		for y in xrange(self.map_h):
			tile_list.append([])
			self.tiles.append([])
			for x in xrange(self.map_w):
				byte = unpack("<B", f.read(1))[0]
				tile_list[y].append(byte)
				self.tiles[y].append(Tile(x, y))

		self.tile_list = tile_list
		f.close()

	def import_tileset(self, img_file):
		"""
		Import a Tileset Image
		"""

		tiles = pygame.image.load(img_file)
		tile_map_size = tiles.get_size()

		tiledata = []
		for y in xrange(tile_map_size[1]  / FLD_TILE_SZ):
			for x in xrange(tile_map_size[0]  / FLD_TILE_SZ):
				tiledata.append(tiles.subsurface((x * FLD_TILE_SZ, y * FLD_TILE_SZ), (FLD_TILE_SZ, FLD_TILE_SZ)))

		self.tile_set = tiledata

	def generate_map(self):
		"""
		Generates Tile Map from Tile List, Tile Set
		"""

		mapimg = pygame.Surface((self.map_w * FLD_TILE_SZ, self.map_h  * FLD_TILE_SZ), depth=32)

		for y, z in enumerate(self.tile_list):
			for x, t in enumerate(z):
				mapimg.blit(self.tile_set[t], (x * FLD_TILE_SZ, y * FLD_TILE_SZ))

		return mapimg

	def update(self):
		if self.animating != [[],[]]:
			self.slide()
		self.rect.topleft = (self.x, self.y)

	def move(self, key, mod):
		self.mod = mod
		if (key == K_UP and self.rect.top < 0) \
		or (key == K_RIGHT \
			and (self.rect.right - self.screen_rect.width) > self.right_overage) \
		or (key == K_DOWN \
			and (self.rect.bottom + 100 - FLD_TILE_SZ - self.screen_rect.height) > self.bottom_overage) \
		or (key == K_LEFT and self.rect.left < 0):
			#self.animating.append(key) - not used?
			return key
		else:
			return 0

	def r_move(self, key, mod):
		moved = self.move(key, mod)
		if moved:
			if key == K_UP: self.animating[1].append(moved and K_DOWN)
			elif key == K_RIGHT: self.animating[0].append(moved and K_LEFT)
			elif key == K_DOWN: self.animating[1].append(moved and K_UP)
			elif key == K_LEFT: self.animating[0].append(moved and K_RIGHT)
		return self.animating


	def colorize(self, color, tilelist):
		# creates a coloured surface for layer 2
		self.overlay = pygame.sprite.Sprite()
		self.overlay.image = pygame.Surface(self.rect.size)
		self.overlay.rect = self.rect
		self.overlay.image.fill((255,0,0))
		self.overlay.image.set_alpha(96)

		self.scenario.layers[2].add(self.overlay)
